var tr_select;
function redondear(amount) {
    var val = parseFloat(amount);
    if (isNaN(val)) {
        return "0.00";
    }
    if (val <= 0) {
        return "0.00";
    }
    val += "";
    // Next two lines remove anything beyond 2 decimal places
    if (val.indexOf('.') == -1) {
        return val + ".00";
    }
    else {
        val = val.substring(0, val.indexOf('.') + 3);
    }
    val = (val == Math.floor(val)) ? val + '.00' : ((val * 10 ==
            Math.floor(val * 10)) ? val + '0' : val);
    return val;
}

function edit_tr(tr) {
    tr_select = tr;
    var id = tr.parent().parent().parent().children("td").children("input#id").val();
    var name = tr.parent().parent().parent().children("td").children("input#name").val();
    var quantity = tr.parent().parent().parent().children("td").children("input#quantity").val();
    var price = tr.parent().parent().parent().children("td").children("div").children("input#price").val();
    //var total = tr.parent().parent().parent().children("td").children("div").children("input#total").val();

    $("#txt_search_product").val(name);
    $('#aux_product_id').val(id);
    $('#txt_stock_product').val("");
    $('#txt_price_product').val(price);
    $('#txt_quantity_product').val(quantity);
    $('#btn_dialog_product_editar').show();
    $('#btn_dialog_product_select').hide();
    $('#div_dialog_product').modal('show');
}

function drop_tr(tr) {
    var total = tr.parent().parent().parent().children("td").children("div").children("input#total").val();
    var tol = parseFloat($("#total_g").val()) - parseFloat(total);
    $("#total_g").val(redondear(tol));
    $("#igv_g").val(redondear(tol * 0.18));
    $("#subtotal_g").val(redondear(tol - tol * 0.18));
    tr.parent().parent().parent().remove();
}

jQuery(document).ready(function($) {

    $("#emission_date").datepicker();
    $("#cancellation_date").datepicker();

    $('#btn_dialog_show_client').click(function() {
        $("#txt_search_client").val("");
        $('#div_dialog_client').modal('show');
    });

    $('#btn_dialog_client_select').click(function() {
        $('#client_id').val($('#aux_client_id').val());
        $('#client_name').val($('#aux_client_name').val());
        $('#client_ruc').val($('#aux_client_ruc').val());
        $('#client_address').val($('#aux_client_address').val());
        $('#div_dialog_client').modal('hide');
    });

    $("#txt_search_client").autocomplete({
        source: "client_search.php",
        minLength: 2,
        select: function(event, ui) {//, ui.item.id, this.value  
            $('#aux_client_id').val(ui.item.id);
            $('#aux_client_name').val(ui.item.name);
            $('#aux_client_ruc').val(ui.item.ruc);
            $('#aux_client_address').val(ui.item.address);
        }
    });
//------------------------------------------------------------------------------
    $('#btn_dialog_show_product').click(function() {
        $("#txt_search_product").val("");
        $('#aux_product_id').val("");
        $('#txt_stock_product').val("");
        $('#txt_price_product').val("");
        $('#txt_quantity_product').val("");
        $('#btn_dialog_product_editar').hide();
        $('#btn_dialog_product_select').show();
        $('#div_dialog_product').modal('show');
    });

    $("#txt_search_product").autocomplete({
        source: "product_search.php",
        minLength: 2,
        select: function(event, ui) {//ui.item.value, ui.item.id, this.value  
            $('#aux_product_id').val(ui.item.id);
            $('#txt_stock_product').val(ui.item.quantity);
            $('#txt_price_product').val(ui.item.price);
        }
    });

    $('#btn_dialog_product_select').click(function() {

        if ($("#aux_product_id").val() == "") {
            alert("Error ingrese : Producto");
            return;
        }
        if (!parseFloat($("#txt_quantity_product").val()) > 0) {
            alert("Error Cantidad : debe ser mayor a cero");
            return;
        }
        if (parseFloat($("#txt_quantity_product").val()) > parseFloat($("#txt_stock_product").val())) {
            alert("Error Cantidad : debe ser menor o igual al stock");
            return;
        }

        $("#detail tbody").append("<tr class=\"item-row\">" +
                "<td>" +
                "<input type=\"hidden\" id=\"id\" value=\"" + $('#aux_product_id').val() + "\" >" +
                "<input type=\"text\" id=\"name\" value=\"" + $('#txt_search_product').val() + "\" readonly=\"readonly\" class=\"form-control input-sm\">" +
                "</td>" +
                "<td>" +
                "<input type=\"text\" id=\"quantity\" value=\"" + $('#txt_quantity_product').val() + "\" readonly=\"readonly\" class=\"form-control input-sm\"  style=\"text-align:right\" >" +
                "</td>" +
                "<td>" +
                "<div class=\"input-group\">" +
                "<span class=\"input-group-addon\">S/.</span>" +
                "<input type=\"text\" id=\"price\" value=\"" + redondear($('#txt_price_product').val()) + "\" class=\"form-control input-sm\" readonly=\"readonly\"  style=\"text-align:right\" >" +
                "</div>" +
                "</td>" +
                "<td>" +
                "<div class=\"input-group\">" +
                "<span class=\"input-group-addon\">S/.</span>" +
                "<input type=\"text\" readonly=\"readonly\" id=\"total\" value=\"" + redondear(parseFloat($("#txt_quantity_product").val()) * parseFloat($("#txt_price_product").val())) + "\" class=\"form-control input-sm\"  style=\"text-align:right\" >" +
                "</div>" +
                "</td>" +
                "<td>" +
                "<div class=\"input-group\">" +
                "<span onclick=\"edit_tr($( this ));\" style=\"cursor: pointer;\" class=\"input-group-addon\"><i class=\"fa fa-edit lblue\"></i></span>" +
                "<span onclick=\"drop_tr($( this ));\" class=\"input-group-addon\"  style=\"cursor: pointer;\" ><i class=\"fa fa-trash-o red\"></i></span>" +
                "</div>" +
                "</td>" +
                "</tr>");



        var precio = parseFloat($('#txt_price_product').val());
        var cantidad = parseFloat($('#txt_quantity_product').val());
        var subtotal = redondear(precio * cantidad);

        var tol = parseFloat($("#total_g").val()) + parseFloat(subtotal);

        $("#total_g").val(redondear(tol));
        $("#igv_g").val(redondear(tol * 0.18));
        $("#subtotal_g").val(redondear(tol - tol * 0.18));

        $('#div_dialog_product').modal('hide');
    });

    $('#btn_dialog_product_editar').click(function() {
        var total_old = tr_select.parent().parent().parent().children("td").children("div").children("input#total").val();

        tr_select.parent().parent().parent().children("td").children("input#id").val($('#aux_product_id').val());
        tr_select.parent().parent().parent().children("td").children("input#name").val($('#txt_search_product').val());
        tr_select.parent().parent().parent().children("td").children("input#quantity").val($('#txt_quantity_product').val());
        tr_select.parent().parent().parent().children("td").children("div").children("input#price").val(redondear($('#txt_price_product').val()));
        tr_select.parent().parent().parent().children("td").children("div").children("input#total").val(redondear(parseFloat($("#txt_quantity_product").val()) * parseFloat($("#txt_price_product").val())));

        var precio = parseFloat($('#txt_price_product').val());
        var cantidad = parseFloat($('#txt_quantity_product').val());
        var subtotal = redondear(precio * cantidad);
        var tol = parseFloat($("#total_g").val()) + parseFloat(subtotal) - parseFloat(total_old);
        $("#total_g").val(redondear(tol));
        $("#igv_g").val(redondear(tol * 0.18));
        $("#subtotal_g").val(redondear(tol - tol * 0.18));
        $('#div_dialog_product').modal('hide');
    });
    //--------------------------------------------------------------------------
    $('#add_invoice').click(function() {
        if ($("#serie").val() == "") {
            alert("Error ingrese : Serire");
            return;
        }
        if ($("#numero").val() == "") {
            alert("Error ingrese : Numero");
            return;
        }
        if ($("#client_id").val() == "") {
            alert("Error ingrese : Proveedor");
            return;
        }
        if ($("#emission_date").val() == "") {
            alert("Error ingrese : Fecha de Emision");
            return;
        }
        if (parseFloat($("#total_g").val()) == 0) {
            alert("Error Total no puede ser cero");
            return;
        }


        var headerjson = $.parseJSON('{"serie": "' + $("#serie").val() + '","number":"' + $("#numero").val() + '","client_id":"' + $("#client_id").val() + '","emission_date":"'
                + $("#emission_date").val() + '","cancellation_date":"' + $("#cancellation_date").val() +
                '","subtotal":"' + $("#subtotal_g").val() + '","igv":"' + $("#igv_g").val() + '","total":"' + $("#total_g").val() + '"}');
        var details = '[';
        $('#detail tbody tr').each(function() {
            details +=
                    '{"id":"' + $(this).children("td").children("input#id").val() + '",' +
                    '"quantity":"' + $(this).children("td").children("input#quantity").val() + '",' +
                    '"price":"' + $(this).children("td").children("div").children("input#price").val() + '",' +
                    '"total":"' + $(this).children("td").children("div").children("input#total").val() + '"},';
        });
        details = details.substring(0, details.length - 1);
        details += ']';
        var detailsjson = $.parseJSON(details);

        $.post("sale_create.php", {
            header: headerjson,
            details: detailsjson
        }).done(function(data) {

            window.location.href = "/erp/module/sale/sale/";
        }).fail(function(jqXHR, textStatus) {
            alert("Error: " + textStatus);
        });
    });
});
